﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using wenku8.Entity;
using wenku8.Parser;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace wenku8.Xamls
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class RepliesPage : Page
    {
        private static ScrollViewer ReplyScrollViewer;

        public RepliesPage()
        {
            this.InitializeComponent();
            ReplyScrollViewer = replyScrollViewer;

            MainPage.PostCommentEvent += PostComment;
            MainPage.ReturnTopEvent += ReturnTop;
        }

        private void ReturnTop(object sender, EventArgs e)
        {
            replyScrollViewer?.ChangeView(null, 0, null);
        }

        private void PostComment(object sender, EventArgs e)
        {

        }

        // 当行至本页面时触发
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            MainPage.DisableReturnTopButton();

            var comment = e.Parameter as Comment;
            commentGrid.DataContext = comment;

            var htmlPage = await HTMLParser.GetHtmlString(comment.CommentUri);
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(htmlPage);
            var contentNode = htmlDocument.GetElementbyId("content");
            var tables = contentNode.SelectNodes(contentNode.XPath + "//table[@class=\"grid\"]");
            tables.RemoveAt(1);
            tables.RemoveAt(0);
            tables.Remove(tables.Last());
            var replies = new ObservableCollection<Comment>();
            CommentParser.GetRepliesAsync(replies, tables);
            replyListView.ItemsSource = replies;

            MainPage.DisableProgressRing();

            base.OnNavigatedTo(e);
        }

        // 控制滚动到顶部按钮的可见性
        private void replyScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (replyScrollViewer.VerticalOffset > replyScrollViewer.ActualHeight)
                MainPage.EnableReturnTopButton();
            else
                MainPage.DisableReturnTopButton();
        }
    }
}
